﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.system.Entitys.Dto.QmsBaseOverduesetting;
using SHZY.system.Entitys;
using SHZY.system.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace SHZY.system;

/// <summary>
/// 业务实现：红绿灯设置.
/// </summary>
[ApiDescriptionSettings(Tag = "system", Name = "QmsBaseOverduesetting", Order = 200)]
[Route("api/system/[controller]")]
public class QmsBaseOverduesettingService : IQmsBaseOverduesettingService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseOverduesettingEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseOverduesettingService"/>类型的新实例.
    /// </summary>
    public QmsBaseOverduesettingService(
        ISqlSugarRepository<QmsBaseOverduesettingEntity> qmsBaseOverduesettingRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseOverduesettingRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
    }

    /// <summary>
    /// 获取红绿灯设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseOverduesettingInfoOutput>();
    }

    /// <summary>
    /// 获取红绿灯设置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var recipientList = input.recipientList?.Split(',').ToList().Last();
        var data = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.type), it => it.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.status), it => it.Status.Equals(input.status))
            .WhereIF(!string.IsNullOrEmpty(input.timeUnit), it => it.TimeUnit.Equals(input.timeUnit))
            .WhereIF(!string.IsNullOrEmpty(input.recipientList), it => it.RecipientList.Contains(recipientList))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Type.Contains(input.keyword) || it.Status.Contains(input.keyword) || it.TimeUnit.Contains(input.keyword) || it.RecipientList.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseOverduesettingListOutput
            {
                id = it.Id,
                type = SqlFunc.Subqueryable<DictionaryDataEntity>().Where(dic => dic.Id.Equals(it.Type) && dic.DictionaryTypeId.Equals("459581510966602757")).Select(dic => dic.FullName),
                minValue = it.MinValue,
                maxValue = it.MaxValue,
                recipientList = it.RecipientList,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);

            await _repository.Context.ThenMapperAsync(data.list, async item =>
            {
                // 状态，即将逾期=1 逾期=2
                var statusData = "[{\"id\":\"1\",\"fullName\":\"即将逾期\"},{\"id\":\"2\",\"fullName\":\"逾期\"}]".ToObject<List<StaticDataModel>>();
                item.status = statusData.Find(it => item.status.Equals(it.id)).fullName;

                // 时间单位 day=天 hour=小时 minute=分钟 second=秒
                var timeUnitData = "[{\"id\":\"day\",\"fullName\":\"天\"},{\"id\":\"hour\",\"fullName\":\"小时\"},{\"id\":\"minute\",\"fullName\":\"分钟\"},{\"id\":\"second\",\"fullName\":\"秒\"}]".ToObject<List<StaticDataModel>>();
                item.timeUnit = timeUnitData.Find(it => item.timeUnit.Equals(it.id)).fullName;

                // 消息接收人
                var recipientListRecipientList = item.recipientList.ToObject<List<string>>();
                item.recipientList = string.Join(",", await _repository.Context.Queryable<UserEntity>().Where(a => recipientListRecipientList.Contains(a.Id)).Select(a => a.RealName).ToListAsync());

                // 消息模板
                var messageTemplateData = "[]".ToObject<List<StaticDataModel>>();
                item.messageTemplate = messageTemplateData.Find(it => item.messageTemplate.Equals(it.id)).fullName;

            });

        return PageResult<QmsBaseOverduesettingListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建红绿灯设置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseOverduesettingCrInput input)
    {
        var entity = input.Adapt<QmsBaseOverduesettingEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取红绿灯设置无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var recipientList = input.recipientList?.Split(',').ToList().Last();
        return await _repository.Context.Queryable<QmsBaseOverduesettingEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.type), it => it.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.status), it => it.Status.Equals(input.status))
            .WhereIF(!string.IsNullOrEmpty(input.timeUnit), it => it.TimeUnit.Equals(input.timeUnit))
            .WhereIF(!string.IsNullOrEmpty(input.recipientList), it => it.RecipientList.Contains(recipientList))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Type.Contains(input.keyword) || it.Status.Contains(input.keyword) || it.TimeUnit.Contains(input.keyword) || it.RecipientList.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseOverduesettingListOutput
            {
                id = it.Id,
                type = SqlFunc.Subqueryable<DictionaryDataEntity>().Where(dic => dic.Id.Equals(it.Type) && dic.DictionaryTypeId.Equals("459581510966602757")).Select(dic => dic.FullName),
                minValue = it.MinValue,
                maxValue = it.MaxValue,
                recipientList = it.RecipientList,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();

            await _repository.Context.ThenMapperAsync(list, async item =>
            {
                // 状态，即将逾期=1 逾期=2
                var statusData = "[{\"id\":\"1\",\"fullName\":\"即将逾期\"},{\"id\":\"2\",\"fullName\":\"逾期\"}]".ToObject<List<StaticDataModel>>();
                item.status = statusData.Find(it => item.status.Equals(it.id)).fullName;

                // 时间单位 day=天 hour=小时 minute=分钟 second=秒
                var timeUnitData = "[{\"id\":\"day\",\"fullName\":\"天\"},{\"id\":\"hour\",\"fullName\":\"小时\"},{\"id\":\"minute\",\"fullName\":\"分钟\"},{\"id\":\"second\",\"fullName\":\"秒\"}]".ToObject<List<StaticDataModel>>();
                item.timeUnit = timeUnitData.Find(it => item.timeUnit.Equals(it.id)).fullName;

                // 消息接收人
                var recipientListRecipientList = item.recipientList.ToObject<List<string>>();
                item.recipientList = string.Join(",", await _repository.Context.Queryable<UserEntity>().Where(a => recipientListRecipientList.Contains(a.Id)).Select(a => a.RealName).ToListAsync());

                // 消息模板
                var messageTemplateData = "[]".ToObject<List<StaticDataModel>>();
                item.messageTemplate = messageTemplateData.Find(it => item.messageTemplate.Equals(it.id)).fullName;

            });

            return list;
    }

    /// <summary>
    /// 导出红绿灯设置.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var exportData = new List<QmsBaseOverduesettingListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseOverduesettingListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"单据类型\",\"field\":\"type\"},{\"value\":\"状态\",\"field\":\"status\"},{\"value\":\"时间单位\",\"field\":\"timeUnit\"},{\"value\":\"时间最小值\",\"field\":\"minValue\"},{\"value\":\"时间最大值\",\"field\":\"maxValue\"},{\"value\":\"消息接收人\",\"field\":\"recipientList\"},{\"value\":\"消息模板\",\"field\":\"messageTemplate\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "红绿灯设置.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseOverduesettingListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除红绿灯设置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除红绿灯设置
                await _repository.Context.Deleteable<QmsBaseOverduesettingEntity>().In(it => it.Id,ids).ExecuteCommandAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新红绿灯设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseOverduesettingUpInput input)
    {
        var entity = input.Adapt<QmsBaseOverduesettingEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new 
        {
            it.Type,
            it.Status,
            it.TimeUnit,
            it.MinValue,
            it.MaxValue,
            it.RecipientList,
            it.MessageTemplate,
            it.EnabledMark,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除红绿灯设置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<QmsBaseOverduesettingEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}